// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package roadmap_dao

import (
	"context"
	"time"

	"gitcode.com/lvupclub/lvup-api/dao/common"
	"gitcode.com/lvupclub/proto-gen-go.git/src/roadmap_member_api"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
)

type InviteInfoDbItem struct {
	InviteCode string `bson:"_id"`
	RoadmapId  string `bson:"roadmapId"`
	CreateTime int64  `bson:"createTime"`
	ExpireTime int64  `bson:"expireTime"`
}

func (item *InviteInfoDbItem) ToInviteInfo() *roadmap_member_api.InviteInfo {
	return &roadmap_member_api.InviteInfo{
		InviteCode: item.InviteCode,
		RoadmapId:  item.RoadmapId,
		CreateTime: item.CreateTime,
		ExpireTime: item.ExpireTime,
	}
}

type _InviteInfoDao struct {
	mc *mongo.Collection
}

func newInviteInfoDao(db *mongo.Database) (*_InviteInfoDao, error) {
	mc := db.Collection(common.DB_NS_ROADMAP + "invite")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"roadmapId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_InviteInfoDao{mc: mc}, nil
}

func (db *_InviteInfoDao) Insert(ctx context.Context, dbItem *InviteInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_InviteInfoDao) Get(ctx context.Context, inviteCode string) (*InviteInfoDbItem, error) {
	retItem := &InviteInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": inviteCode}).Decode(retItem)
	return retItem, err
}

func (db *_InviteInfoDao) Exist(ctx context.Context, inviteCode string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": inviteCode})
	return count > 0, err
}

func (db *_InviteInfoDao) Remove(ctx context.Context, inviteCode, roadmapId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": inviteCode, "roadmapId": roadmapId})
	return err
}

func (db *_InviteInfoDao) RemoveByRoadmap(ctx context.Context, roadmapId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"roadmapId": roadmapId})
	return err
}

func (db *_InviteInfoDao) RemoveExpire(ctx context.Context, roadmapId string) error {
	nowTime := time.Now().UnixMilli()
	_, err := db.mc.DeleteMany(ctx, bson.M{"roadmapId": roadmapId, "expireTime": bson.M{"$lt": nowTime}})
	return err
}

func (db *_InviteInfoDao) List(ctx context.Context, roadmapId string) ([]*InviteInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"roadmapId": roadmapId})
	if err != nil {
		return nil, err
	}
	retList := []*InviteInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
